import os
import xlrd

BASE_DIR = os.path.dirname(__file__)


class ExcelOp(object):

    def __init__(self, ex_file):
        self.ex_file = ex_file
        self.ex_data = xlrd.open_workbook(self.ex_file)

    def get_table(self, index=None, sheet_name=None):
        """
        :param index:
        :param sheet_name:
        :return:
        """
        if sheet_name:
            table = self.ex_data.sheet_by_name(sheet_name)  # 通过sheet名获取表
            return table
        if not index:
            index = 0
        table = self.ex_data.sheet_by_index(index)  # 通过sheet 的索引获取表
        return table

    def excel_run(self):
        table = self.get_table()
        row_values = table.row_values(0)  # 读取0行所有数据
        col_values = table.col_values(0)  # 读取0列所有数据
        print(row_values)
        print(col_values)
        num_rows = table.nrows  # 获取总行数
        num_cols = table.ncols  # 获取总列数

        # 遍历行数，获取每行的值
        for row in range(num_rows):
            row_values = table.row_values(row)  # 得到每行的值--列表
            print(row_values)
            for col in range(num_cols):
                cell = table.cell(row, col).value   # 得到每个单元格的值
                print(cell)


if __name__ == '__main__':
    ex_name = 'test.xlsx'
    ex_file = os.path.join(BASE_DIR, ex_name)
    ex = ExcelOp(ex_file=ex_file)
    ex.excel_run()
